<template>
  <el-form :inline="true">
    <el-form-item label="商品编码/商品名称">
      <el-input v-model="queryConditions.combine" style="width: 200px" size="large" placeholder="请输入"
        :suffix-icon="Search" clearable />
    </el-form-item>
      <el-form-item label="所属分类" prop="kid">
        <el-tree-select
          v-model="queryConditions.kid"
          :data="kindOptions"
          check-strictly
          :props="{ 
            value: 'value', 
            label: 'label', 
            children: 'children' 
          }"
          placeholder="请选择分类"
          style="width: 200px"
          clearable
          :render-after-expand="false"
        />
    </el-form-item>
      <el-button type="primary" :icon="Search" @click="search">查询</el-button>
      <el-button type="primary" :icon="RefreshRight" @click="reset">重置</el-button>
    </el-form>
    <TestPage :table-data="formattedTableData" :columns="tableColumns" :current-page="pageNo" :total="allPage"
      :page-size="pageSize" @page-change="handlePageChange" @action="handleTableAction" @edit="handleEditAction"
      @delete="handleDeleteAction" />

    <!-- 弹窗显示 AddCustomer -->
    <el-dialog title="新增商品" v-model="showAddDialog" width="40%" :before-close="handleDialogClose">
      <AddGood @submit-success="handleAddSuccess" @cancel="handleDialogClose" />
    </el-dialog>
    <!-- 编辑客户弹窗 -->
    <el-dialog title="编辑商品" v-model="showEditDialog" width="40%" :before-close="handleDialogClose">
      <AddGood :good="editingGood" @submit-success="handleEditSuccess" @cancel="handleDialogClose" />
    </el-dialog>
</template>

<script setup lang="ts">
import TestPage from "@/test/TestPage.vue"
import AddGood from "./AddGood.vue";
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { ref, computed, reactive,onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus'
import type { Good } from '@/types/basic/good';
import axios from "axios";

let pageNo = ref(1)
let pageSize = ref(3)
let allPage = ref(0)

// 下拉选项
interface Option { value: number, label: string }
const unitOptions = ref<Option[]>([])

interface TreeNode {
  value: number
  label: string
  children?: TreeNode[]
}

// 响应式变量声明
const kindOptions = ref<TreeNode[]>([])

// 获取分类数据方法
async function loadKindOptions() {
  try {
    const response = await axios.post('basic/goodsCategory/showGoodsCategoryByTree')
    const rawData = response.data.data
    kindOptions.value = convertTreeData(rawData)
    console.log('处理后的分类数据:', kindOptions.value)
  } catch (e: any) {
    ElMessage.error('加载分类失败: ' + e.message)
  }
}

// 树形数据转换函数
function convertTreeData(nodes: any[]): TreeNode[] {
  return nodes.map(node => ({
    value: node.id,
    label: node.name,
    children: node.children ? convertTreeData(node.children) : []
  }))
}

console.log(kindOptions)

//查询条件
const queryConditions = reactive({
  combine: '',
  kid: ''
})

const tableColumns = ref([
  { prop: 'id', label: '序号' },
  { prop: 'code', label: '商品编码' },
  { prop: 'name', label: '商品名称' },
  { prop: 'kname', label: '商品种类' },
  { prop: 'uname', label: '单位名称' },
  { prop: 'tax', label: '税率' },
  { prop: 'createDate', label: '创建时间' },
  { prop: 'createUser', label: '创建人' },
  { prop: 'updateDate', label: '更新时间' },
  { prop: 'updateUser', label: '更新人' }
  // {prop: 'isDelete', label: '是否删除'},


])
let tableData = ref<Good[]>([])
// 计算属性
const formattedTableData = computed(() => {
  return tableData.value.map(item => ({
    ...item,
    // isDelete: item.isDelete === 0 ? '否' : '是'
  }));
});

const showAddDialog = ref(false); // 新增弹窗
const showEditDialog = ref(false); // 编辑弹窗
const editingGood = ref<Good | null>(null); // 当前编辑的客户

const handlePageChange = (newPage: number) => {
  pageNo.value = newPage

  fetchData(newPage)
}


const handleTableAction = (actionName: string) => {
  console.log('触发操作:', actionName)
  // 处理具体业务逻辑
  if (actionName === 'add') {
    showAddDialog.value = true; // 打开新增弹窗
  }
}

//修改弹窗
const handleEditAction = (good: Good) => {
  editingGood.value = { ...good }; // 复制客户数据
  showEditDialog.value = true; // 打开修改弹窗
};

const handleDeleteAction = async (good: Good) => {
  try {
    await ElMessageBox.confirm('确定删除此客户？此操作不可恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await axios.post(`basic/good/delGood?id=${good.id}`,);
    ElMessage.success('删除成功');
    await fetchData(pageNo.value); // 刷新
  } catch (error) {
    ElMessage.error('删除失败，请稍后重试');
    console.error('删除失败:', error);
  }
};

const handleAddSuccess = () => {
  showAddDialog.value = false;
  fetchData(pageNo.value); // 刷新
  ElMessage.success('新增商品成功');
};

const handleEditSuccess = () => {
  showEditDialog.value = false;
  editingGood.value = null;
  fetchData(pageNo.value); // 刷新表格
  ElMessage.success('更新商品成功');
};

const handleDialogClose = () => {
  ElMessageBox.confirm('确定关闭新增客户窗口？未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    showAddDialog.value = false; // 确认关闭
    showEditDialog.value = false;
  })
};

//查询
const search = () => {
  pageNo.value = 1; // 重置到第一页
  fetchData(1);
};

// 重置函数
const reset = () => {
  queryConditions.combine = ''
  queryConditions.kid = ''
  pageNo.value = 1
  fetchData(1)
}


async function fetchData(page: number) {
  try {
    if(queryConditions.kid==undefined){
      queryConditions.kid=''
    }
    const params = new URLSearchParams();
    params.append('pageNow', page.toString());
    params.append('pageSize', pageSize.value.toString());
    params.append('combine', queryConditions.combine);
    params.append('kid', queryConditions.kid);
    console.log(queryConditions.kid)
    let response = await axios.post('basic/good/getGoodPage', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    tableData.value = response.data.data.list || [];
    allPage.value = response.data.data.total || 0;
  } catch (error) {
    ElMessage.error('获取商品数据失败');
    tableData.value = [];
    allPage.value = 0;
    console.error('获取数据失败:', error);
  }
}

onMounted(async () => {
  await loadKindOptions();
});
fetchData(1)
</script>


<style scoped></style>
